<template>
  <div class="resume">
    <div>
      <div class="title">
        <h1 style="color: #4D7181;font-size: 40px">反馈举报</h1>
        <div>
          <ExceptionOutlined class="icon"/>
          <ZoomInOutlined class="icon"/>
        </div>

      </div>
    </div>
    <div style="border: 2px solid #4D7181; padding: 20px;border-top: 30px solid #4D7181; border-radius: 10px">


      <a-form
          ref="formRef"
          :label-col="labelCol"
          :model="formState"
          :rules="rules"
          :wrapper-col="wrapperCol"
      >
        <a-divider orientation="left" style="color:#4D7181; font-size: 20px">基本信息</a-divider>
        <div class="basic">
          <div class="basicInfo">
            <a-form-item ref="reportCheckStatus" label="审核状态" name="reportCheckStatus" style="width: 200px">
              <a-input v-model:value="formState.reportCheckStatus" :bordered="false" :disabled="true"/>
            </a-form-item>
            <a-form-item ref="reportStatus" label="举报状态" name="reportStatus" style="width: 200px">
              <a-input v-model:value="formState.reportStatus" :bordered="false" :disabled="true"/>
            </a-form-item>
            <div style="width: 90%">

            </div>
            <a-form-item ref="reportPersonName" label="姓名" name="reportPersonName" style="width: 200px">
              <a-input v-model:value="formState.reportPersonName" :bordered="isBordered" :disabled="!isBordered"/>
            </a-form-item>
            <a-form-item ref="reportPersonAccount" label="账号" name="reportPersonAccount" style="width: 200px">
              <a-input v-model:value="formState.reportPersonAccount" :bordered="isBordered" :disabled="!isBordered"/>
            </a-form-item>

            <a-form-item ref="reportPersonContact" label="联系方式" name="reportPersonContact">
              <a-input v-model:value="formState.reportPersonContact" :bordered="isBordered" :disabled="!isBordered" style="width: 300px"/>
            </a-form-item>
          </div>
        </div>
        <a-divider orientation="left" style="color:#4D7181; font-size: 20px">举报信息</a-divider>
        <div class="school">
          <div v-show="formState.reportCheckStatus==='审核不通过'">
            <a-form-item ref="reportCheckRemark" label="拒绝原因"
                         name="reportCheckRemark">
              <a-textarea v-model:value="formState.reportCheckRemark"
                          :auto-size="{minRows: 3, maxRows: 20}"
                          show-count
                          style="width: 500px"
              />
            </a-form-item>
          </div>

          <div>
            <a-form-item ref="reportDescribe" label="举报描述" name="reportDescribe">
              <a-textarea v-model:value="formState.reportDescribe"
                          :auto-size="{minRows: 3, maxRows: 20}"
                          :disabled="!isBordered"
                          :maxlength="600"
                          show-count
                          style="width: 800px "
              />
            </a-form-item>
            <!--          占位换行-->
            <a-form-item ref="intentionContactInfo" label="佐证信息" name="intentionContactInfo" >
              <div class="clearfix" >
                <a-upload
                    v-model:file-list="fileList"
                    action="http://localhost:8080/image/upload"
                    list-type="picture-card"
                    @change="handleChange"
                    @preview="handlePreview"
                    @remove="handleRemove"
                >
                  <div v-if="fileList.length < 4&&isBordered">
                    <plus-outlined />
                    <div style="margin-top: 8px">Upload</div>
                  </div>
                </a-upload>
                <a-modal :footer="null" :open="previewVisible" :title="previewTitle" @cancel="handleCancel" >
                  <img :src="previewImage" alt="example" style="width: 100%"/>
                </a-modal>
              </div>
            </a-form-item>
          </div>
        </div>

        <a-col :span="24">
          <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
            <div>
              <div v-if="isSave">
                <div style="display:flex;">
                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定保存吗？" @confirm="save">
                    <a-button style="width:200px" type="primary">保存</a-button>
                  </a-popconfirm>
                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定重置吗？" @confirm="resetForm">
                    <a-button danger style="margin-left: 60px; width:200px" type="primary">重置</a-button>
                  </a-popconfirm>
                </div>
              </div>
              <div v-else>
                <div v-if="isUpdate" style="display:flex;">
                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定保存吗？" @confirm="update">
                    <a-button style="width:200px" type="primary">保存</a-button>
                  </a-popconfirm>

                  <a-button style="margin-left: 60px; width:200px" @click="cancel">取消</a-button>

                  <a-popconfirm cancel-text="取消" ok-text="确定" title="你确定重置吗？" @confirm="resetForm">
                    <a-button danger style="margin-left: 60px; width:200px" type="primary">重置</a-button>
                  </a-popconfirm>
                </div>
                <div v-else style="display:flex;">
                  <a-popconfirm v-if="(formState.reportStatus ==='举报已成立'|| formState.reportStatus ==='举报已撤回') " cancel-text="取消" ok-text="确定"
                                title="你确定再添加举报吗？" @confirm="resetForm">
                    <a-button style="width:200px" type="primary">再添加举报</a-button>
                  </a-popconfirm>

                  <a-popconfirm v-else cancel-text="取消" ok-text="确定" title="你确定修改吗？" @confirm="isupdate">
                    <a-button style="width:200px" type="primary">修改</a-button>
                  </a-popconfirm>

                  <a-button style="margin-left: 60px; width:200px" @click="goBack">返回</a-button>

                  <a-popconfirm v-if="formState.reportStatus ==='举报中' " cancel-text="取消" ok-text="确定"
                                title="你确定测回举报吗？" @confirm="cancelReport">
                    <a-button danger style="margin-left: 60px; width:200px" type="primary">撤回举报</a-button>
                  </a-popconfirm>
                </div>
              </div>
            </div>

          </a-form-item>
        </a-col>
      </a-form>
    </div>
  </div>
</template>
<script setup>
import {h, onMounted, reactive, ref, toRaw} from 'vue';
//修改提示框
import {ExceptionOutlined, SmileOutlined, ZoomInOutlined} from '@ant-design/icons-vue';
//获取当前登录用户信息
import {useUserStore} from "@/stores/user.js";
import {message, notification} from "ant-design-vue";
import {useRouter} from 'vue-router';
import {updateIntentionByIdAPI} from "@/apis/intention.js";
import {queryResumeByStudentUserIdAPI} from "@/apis/student.js";
import {addReportAPI, queryReportByAccountAPI, queryReportImageAPI, updateReportAPI} from "@/apis/report.js";

const formRef = ref();
const formState = reactive({
  reportUserId: '',
  reportUserRole: '',
  reportId: '',
  reportPersonName: '',
  reportPersonAccount: '',
  reportPersonContact: '',
  reportDescribe: '',
  reportStatus: '',
  reportCheckStatus: '',
  reportCheckRemark: '',
  imageList: [],
});
const rules = {};
const useStore = useUserStore();
const save = () => {
  formRef.value
      .validate()
      .then(async () => {
        formState.reportCheckStatus = '审核中';
        formState.reportStatus = '举报中';
        //遍历图片
        for (let i = 0; i < fileList.value.length; i++) {
          formState.imageList[i] = fileList.value[i].response.data;
          console.log(formState.imageList[i])
        }
        const res = await addReportAPI(formState);
        if (res.data.flag) {
          success(res.data.message);
        }

      })
      .catch(error => {
        console.log('error', error);
      });
};
const isUpdate = ref(false);//是否修改
const isBordered = ref(false);//是否边框
const isupdate = () => {//修改按钮
  if(formState.reportCheckStatus === '审核中'){
    openNotification("举报信息正在审核中,不可修改，请耐心等待！", "red", 'top');
  }else {
    isUpdate.value = true;
    isBordered.value = true;
    openNotification("点击照片或输入框均可修改！", "green", 'top');
  }
}
const update = () => {

  formRef.value
      .validate()
      .then(async () => {
        formState.reportCheckStatus = '审核中';
        formState.reportStatus = '举报中';
        formState.imageList = [];
        //遍历图片
        for (let i = 0; i < fileList.value.length; i++) {
          formState.imageList[i] = fileList.value[i].response.data;
        }
        const res = await updateReportAPI(formState);
        console.log(res);
        if (res.data.flag) {
          success("修改成功，请等待审核！");
          openNotification("已提交审核！", "#52C41A");
          // 设置一个定时器，1秒（1000毫秒）后执行页面刷新
          setTimeout(function () {
            location.reload(); // 刷新当前页面
          }, 1000);
        } else {
          console.log('error submit!', toRaw(formState));
        }
      })
      .catch(error => {
        console.log('error', error);
      });
};
//撤回举报
const data = ref({reportId: '', reportStatus: '',reportCheckStatus:''});
const cancelReport = async () => {
  data.reportId = formState.reportId;
  data.reportStatus = '举报已撤回';
  data.reportCheckStatus = '未提交';
  console.log(data.reportId);
  const res = await updateReportAPI(data);
  if (res.data.flag) {
    success("撤回成功！");
    // 设置一个定时器，在1秒后刷新页面
    setTimeout(() => {
      location.reload(); // 刷新当前页面
    }, 1000);
  } else {
    console.log('error submit!', toRaw(formState));
  }
}


const success = (msg) => {
  message.success(msg);
};

//重置后是否刷新
const isRefresh = ref(false);
const resetForm = () => {
  fileList.value = [];
  formState.reportDescribe = '';
  formState.reportCheckRemark = '';
  formState.reportStatus = '';
  formState.imageList = [];
  formState.reportCheckStatus = '';
  isUpdate.value = true;
  isBordered.value = true;
  isRefresh.value = true;
};

//控制按钮
const isSave = ref(true);//是否保存
//获取数据
//获取当前登录用户信息

const User = ref(useStore.userInfo);
const reportId = ref();
const getData = async (User) => {
  formState.reportUserId = User.value.userId;
  formState.reportUserRole = User.value.userRole;
  formState.reportPersonAccount = User.value.account;
  // 等待第一个请求完成
  const res1 = await queryResumeByStudentUserIdAPI(User.value.userId);
  formState.reportPersonName = res1.data.data.studentName;
  formState.reportPersonContact = res1.data.data.studentContact;

  // 等待第二个请求完成
  const res2 = await queryReportByAccountAPI(User.value.account);
  if (res2.data.flag) {
    formState.reportDescribe = res2.data.data.reportDescribe;
    formState.reportStatus =res2.data.data.reportStatus === null ? "未举报" : res2.data.data.reportStatus;
    reportId.value = res2.data.data.reportId;
    formState.reportId = res2.data.data.reportId;
    formState.reportCheckStatus = res2.data.data.reportCheckStatus === null ? "未提交" : res2.data.data.reportCheckStatus;
    formState.reportCheckRemark = res2.data.data.reportCheckRemark;

    isSave.value = false;
    isBordered.value = false;
  }

  // 执行第三个请求（获取图片的请求），此时前两个请求已经确保完成了
  const res3 = await queryReportImageAPI(reportId.value);
  if (res3.data.flag) {
    formState.imageList = res3.data.data;
    console.log(formState.imageList)
    for (let i = 0; i < formState.imageList.length; i++) {
      fileList.value[i] = {
        uid: formState.imageList[i].imageId,
        name: formState.imageList[i].imageUrl,
        status: 'done',
        url: "http://localhost:8080/image/download?name=" + formState.imageList[i].imageUrl,
        response: {
          data: formState.imageList[i].imageUrl,
        }
      };
    }
  }
}


//生命周期
onMounted(() => {
  getData(User);
});

//提示框
const openNotification = (des, col, placement) => {
  notification.open({
    message: '温馨提示！！！',
    description: des, placement,
    icon: () =>
        h(SmileOutlined, {
          style: {color: col},
        }),
  });
};

const router = useRouter();
const goBack = () => {
  router.go(-1); // -1 表示返回上一个页面
}
const cancel = () => {
  isSave.value = false;
  isUpdate.value = false;
  isBordered.value = false;
  if (isRefresh.value) {
    // 设置一个定时器，1秒（1000毫秒）后执行页面刷新
    setTimeout(function () {
      location.reload(); // 刷新当前页面
    }, 500);
  }
}

//上传图片
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
const fileList = ref([]);
const loading = ref(false);
const imageUrl = ref('');
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};
const handleChange = info => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }
  if (info.file.status === 'done') {
    getBase64(info.file.originFileObj, base64Url => {
      imageUrl.value = base64Url;
      loading.value = false;
    });
    formState.student_imgUrl = fileList.value[0].response.data;
  }
  if (info.file.status === 'error') {
    loading.value = false;
    message.error('upload error');
  }
};
const handlePreview = async file => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};
const handleRemove = async file => {
  for (let i = 0; i < formState.imageList.length; i++) {
    if (formState.imageList[i].data === file.response.data && fileList.value[i].uid === file.uid) {
      formState.imageList.splice(i, 1);
    }
  }
};
</script>
<style lang="scss" scoped>
.resume {
  margin: 5px;
  padding: 20px 60px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1), 0 6px 20px rgba(0, 0, 0, 0.1);
  border-radius: 30px; /* 你可以调整这个值来改变圆角的大小 */

  .title {
    display: flex;
    justify-content: space-between;
    //border-bottom: 15px solid #4D7181;

    .icon {
      font-size: 35px;
      padding: 15px;
      color: white;
      margin-right: 20px;
      background-color: #C09E66;
      border-radius: 50px;
      margin-bottom: 10px;
    }
  }

  .basic {
    display: flex;
    padding-left: 30px;

    .basicInfo {
      height: 100%;
      display: flex;
      flex-wrap: wrap; /* 允许子元素换行 */
      gap: 0 30px; /* 设置水平间距为10px，垂直间距为0 */
    }

    .update {
      margin-right: 100px;
    }
  }

  .school {
    width: 100%;
    padding-left: 30px;
    justify-content: space-between;
    display: flex;
    margin-bottom: 30px;
    flex-wrap: wrap; /* 允许子元素换行 */
    gap: 0 30px; /* 设置水平间距为10px，垂直间距为0 */
  }
}

:deep(.ant-form-item) {
  margin-bottom: 10px;
}

:deep(.ant-upload-wrapper.ant-upload-picture-card-wrapper.ant-upload.ant-upload-select) {
  border: 0;
  height: 170px;
  width: 150px;
}

/* 如果组件不在 Shadow DOM 中 */
.ant-upload-wrapper.ant-upload-picture-card-wrapper.ant-upload.ant-upload-select {
  border: none; /* 移除边框 */
  height: 170px;
  width: 150px;
}

</style>

